import HeaderView from "@/component/Header"
import TimeOut from '@/component/TimeOut'
import { Button, Radio, Tag, Toast } from "antd-mobile"
import style from './index.module.scss'
import { GetAddress, DefaultAddress } from '@/api/address'
import { useEffect, useState } from "react"
import { EditSOutline } from 'antd-mobile-icons'
import { useNavigate } from "react-router-dom"
import { addressListType } from '@/type/editAddress'

const Address = () => {
  const [flag, setFlag] = useState(false) // 错误提示 
  const navigate = useNavigate()
  const [addressList, setAddressList] = useState([]) // 地址列表
  const [radioValue, setRadioValue] = useState<string | number>(0) // 默认选中地址的radio

  // 数据初始化
  const init = async () => {
    const res = await GetAddress().catch(err => {
      if (err.code === 'ECONNABORTED' || err.code === 'ERR_NETWORK') setFlag(true)
    })

    try {
      if(res?.status === 200) {
        setAddressList(res.data.data)
        let val = res.data.data.find((item: any) => item.is_default === 1)
        setRadioValue(val.id)
      }
    } catch (error) {
      console.log(error)
    }
  }
  useEffect(() => { init() }, [])
  
  // 地址切换
  const radioClick = async (id: number) => {
    const res = await DefaultAddress(id).catch(err => {
      if (err.code === 'ECONNABORTED' || err.code === 'ERR_NETWORK') {
        Toast.show({icon: 'fail', content: '请稍后再试', duration: 1500, maskClickable: false})
      }
    })

    try {
      if(res?.status === 204) {
        init()
      }
    } catch (error) {
      console.log(error)
    }
  }


  // 地址列表
  const getList = () => {
    return addressList.map((item: addressListType) => {
      return (
        <div className={style.item} key={item.id}>
          <div className={style.itemLeft}>
            <div className={style.leftRadio}><Radio onClick={() => radioClick(item.id)} value={item.id}/></div>
            <div className={style.leftDesc}>
              <p>{item.name}---{item.phone} {item.is_default ? <Tag round color="#2db7f5">默认</Tag> : ''}</p>
              <p className={style.city}>{item.province}---{item.city}---{item.county}</p>
              <p>{item.address}</p>
            </div>
          </div>
          <div className={style.itemRight} onClick={() => navigate('/editAddress', {state: {type: 'edit', id: item.id}})}>
            <EditSOutline fontSize={18}/>
          </div>
        </div>
      )
    })
  }

  return (
   <>
     {/* 头部信息 */}
     <HeaderView title="我的地址" backIcon={true}/>

     {
      addressList.length !== 0
      ?
      <>
       {/* 地址列表 */}
       <div className={style.addressBox}>
          <Radio.Group value={radioValue}>
          {getList()}
          </Radio.Group>
       </div>
      </>
      :
      <p className={style.no}>暂无地址噢!</p>
     }

     {/* 添加地址 */}
     <div className={style.btn}>
        <Button block color='primary' size='large' onClick={() => navigate('/editAddress', {state: {type: 'add'}})}>新增地址</Button>
     </div>
     {/* 错误提示页面 */}
     {flag && <TimeOut/>}
   </>
  )
}
export default Address